<template>
	<view class="page">
		<uni-section class="mb-10" title="全局配置" type="line"></uni-section>
		<uni-list>
			<uni-list-item v-for="(item, index) in configList" :key="index" :title="getTitle(item.label)"
				:note="getNote(item.label)" rightText="右侧文字" clickable>
				<template v-slot:footer>
					<view class="list-item">
						<view class="image" @click="handlePreview(item.value)"
							v-if="item.value && item.label !== 'targetCurrent'">
							<image class="img" :src="item.value" mode="aspectFill"></image>
						</view>
						<uni-number-box v-if="item.label === 'targetCurrent'" :min="-1" :max="21" :value="item.value"
							@change="handleNumberChange($event, index)" />
						<button class="upload-btn" size="mini" @click.stop="handleUpload(index)"
							v-if="item.label !== 'targetCurrent'">上传</button>
					</view>
				</template>
			</uni-list-item>
		</uni-list>
		<ver />
	</view>
</template>

<script setup>
	import ver from '@/components/ver.vue'
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		getConfig,
		updateConfig,
		addConfig
	} from '@/api/config.js';

	const configList = ref([{
			label: 'bg',
			value: '',
			_id: null
		},
		{
			label: 'skull',
			value: '',
			_id: null
		},
		{
			label: 'luffy',
			value: '',
			_id: null
		},
		{
			label: 'robin',
			value: '',
			_id: null
		},
		{
			label: 'targetCurrent',
			value: -1,
			_id: null
		}
	]);

	const getTitle = (label) => {
		const titles = {
			bg: '背景图片',
			skull: '骷髅动画',
			luffy: '路飞动画',
			robin: '罗宾动画',
			targetCurrent: '指定抽奖结果'
		};
		return titles[label] || label;
	};

	const getNote = (label) => {
		const notes = {
			bg: '最底部背景图片 (支持JPG/PNG)',
			skull: '骷髅动画效果 (支持GIF)',
			luffy: '路飞动画效果 (支持GIF)',
			robin: '罗宾动画效果 (支持GIF)',
			targetCurrent: '0-21指定抽奖结果; -1为随机'
		};
		return notes[label] || '';
	};

	const handlePreview = (url) => {
		uni.previewImage({
			urls: [url]
		});
	};

	const handleNumberChange = async (value, index) => {
		const item = configList.value[index];
		item.value = value;

		try {
			if (item._id) {
				await updateConfig(item._id, {
					value: value
				});
			} else {
				const {
					id
				} = await addConfig({
					label: item.label,
					value: value
				});
				item._id = id;
			}

			uni.showToast({
				title: '保存成功',
				icon: 'success'
			});
		} catch (error) {
			uni.showToast({
				title: error.message || '保存失败',
				icon: 'none'
			});
		}
	};

	const handleUpload = async (index) => {
		const item = configList.value[index];
		const accept = item.label === 'bg' ? 'image/*' : 'image/gif';

		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			extension: item.label === 'bg' ? ['.jpg', '.png'] : ['.gif'],
			success: async (res) => {
				const tempFilePath = res.tempFilePaths[0];
				uni.showLoading({
					title: '上传中...'
				});

				try {
					const uploadRes = await uniCloud.uploadFile({
						filePath: tempFilePath,
						cloudPath: `config/${item.label}-${Date.now()}${item.label === 'bg' ? '.jpg' : '.gif'}`
					});

					const fileID = uploadRes.fileID;

					if (item._id) {
						await updateConfig(item._id, {
							value: fileID
						});
					} else {
						const {
							id
						} = await addConfig({
							label: item.label,
							value: fileID
						});
						item._id = id;
					}

					item.value = fileID;
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
				} catch (error) {
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '选择文件失败',
					icon: 'none'
				});
			}
		});
	};

	// 初始化加载配置
	onMounted(async () => {
		try {
			const res = await getConfig();
			configList.value.forEach(configItem => {
				const savedConfig = res.find(item => item.label === configItem.label);
				if (savedConfig) {
					configItem.value = savedConfig.value;
					configItem._id = savedConfig._id;
				}
			});
		} catch (error) {
			uni.showToast({
				title: error.message || '加载配置失败',
				icon: 'none'
			});
		}
	});
</script>

<style lang="scss" scoped>
	.page {
		.list-item {
			display: flex;
			align-items: center;
			gap: 20rpx;

			.image {
				width: 100rpx;
				height: 100rpx;
				border: 2rpx solid #999;
				border-radius: 8rpx;
				overflow: hidden;

				.img {
					display: block;
					width: 100%;
					height: 100%;
				}
			}

			.upload-btn {
				background-color: #55aaff;
				color: #fff;
				border-radius: 8rpx;
				padding: 0 20rpx;
				height: 60rpx;
				line-height: 60rpx;
				font-size: 24rpx;

				&:active {
					opacity: 0.7;
				}
			}
		}
	}
</style>